<?php

namespace app\admin\controller;

use app\common\model\MarketModel;
use think\Db;
use think\Request;
use cmf\controller\AdminBaseController;
use think\Validate;
use tree\Tree;


/*车品超市 商品*/

class GoodsController extends AdminBaseController
{

    /*车品超市列表*/
    public function index()
    {
        $param = input();
        $map = [];
        $map[] = ['is_del', '=', '0'];

        //分类
        if (isset($param['cid']) && !empty($param['cid'])) {
            $cid = $param['cid'];
            //如果cid的pid为0 则查询所有子分类id集合
            $cateData = db('marketcate')->find($cid);
            if ($cateData['parent_id'] == 0) {
                $cidCollets = db('marketcate')->where('parent_id', $cid)->select()->toArray();
                $cidColletArr = [];
                foreach ($cidCollets as $cidCollet) {
                    array_push($cidColletArr, $cidCollet['id']);
                }
                $cidColletstr = implode(',', $cidColletArr);
            } else {
                $cidColletstr = $cid;
            }
            $map[] = ['cid', 'in', $cidColletstr];
        }

        //关键字
        if (isset($param['keywords'])) {
            $map[] = ['title', 'like', '%' . $param['keywords'] . '%'];
        }

        $datas = db('market')
            ->alias('m')
            ->field('m.*,c.name cname')
            ->leftJoin('jzb_marketcate c', 'm.cid= c.id')
            ->where($map)
            ->order('is_tuijian desc,list_orders asc,id desc')
            ->paginate(20);

        //显示分类
        $tree = new Tree();
        $parentId = $this->request->param("cid", 0, 'intval');
        $result = db('marketcate')->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);

        $this->assign(compact('datas'));
        return $this->fetch();
    }

    /*添加商品*/
    public function add()
    {
        //显示分类
        $tree = new Tree();
        $parentId = $this->request->param("parent_id", 0, 'intval');
        $result = db('marketcate')->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);

        $spec_type_list = db("SpecType")->order("id desc")->select();
        $this->assign(compact('spec_type_list'));
        return $this->fetch();
    }

    /*提交商品添加*/
    public function addPost()
    {
        $param = input();
        //验证输入信息
        $rule = [
            'cid' => 'require|number',
            'title' => 'require|unique:market',
            'img' => 'require',
            'banner' => 'require',
            'showprice' => 'require|float',
            'postage' => 'float',
            'spec_type_id' => 'require|number',
            'content' => 'require'];
        $msg = [
            'cid.require' => '请选择一个分类',
            'cid.number' => '分类格式错误',
            'title.require' => '标题不能为空',
            'title.unique' => '标题已存在',
            'img.require' => '请选择一个封面图',
            'banner.require' => '请选择一个轮播图',
            'showprice.require' => '展示价格不能为空',
            'showprice.float' => '展示价格只能是数字',
            'postage.float' => '邮费只能是数字',
            'spec_type_id.require' => '商品类型必须',
            'spec_type_id.number' => '商品类型必须是数字',
            'content.require' => '商品详情标题不能为空'];

        $result = $this->validate($param, $rule, $msg);
        if (true !== $result) {
            $this->error($result);
        }
        //组合轮播图路径
        $param['banner'] = implode('|', $param['banner']);
        $content = $param['content'];
        $param['content'] = htmlspecialchars($content);

        // 启动事务
        Db::startTrans();
        try {
            //添加基础商品数据
            $goods_id = Db::name('market')->strict(false)->insertGetId($param);
            if (!$goods_id) {
                exception('添加基础商品数据出错');
            }
            //处理商品规格
            $marketSpecData = [];
            foreach ($param['spec_price'] as $key => $value) {
                $marketSpecData[] = [
                    'goods_id' => $goods_id,
                    'spec_str' => $key,
                    'stock' => $param['spec_stock'][$key],
                    'image' => $param['image'][$key],
                    'price' => $value,
                    'time' => time()
                ];
            }
            if (!empty($marketSpecData)) {
                $result = Db::name('market_spec')->insertAll($marketSpecData);
                if (!$result) {
                    exception("规格添加错误");
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->success('操作错误' . $e->getMessage());
        }
        $this->success('操作成功', url('index'));
    }

    /*编辑*/
    public function edit()
    {
        $id = input('id', 0);

        //商品详情信息
        $data = db('market')->find($id);

        //显示分类
        $tree = new Tree();
        $parentId = $data['cid'];
        $result = db('marketcate')->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);
        $data['banner'] = explode('|', $data['banner']);

        //商品分类
        $spec_type_list = db("SpecType")->order("id desc")->select();
        $this->assign(compact('spec_type_list'));

        //处理富文本
        $data['content'] = htmlspecialchars_decode($data['content']);
        $this->assign(compact('data'));
        return $this->fetch();
    }

    /*提交编辑*/
    public function editPost()
    {
        $param = input();
        //验证输入信息
        $rule = [
            'cid' => 'require|number',
            'title' => 'require|unique:market',
            'img' => 'require',
            'banner' => 'require',
            'showprice' => 'require|float',
            'postage' => 'float',
            'spec_type_id' => 'require|number',
            'content' => 'require'];
        $msg = [
            'cid.require' => '请选择一个分类',
            'cid.number' => '分类格式错误',
            'title.require' => '标题不能为空',
            'title.unique' => '标题已存在',
            'img.require' => '请选择一个封面图',
            'banner.require' => '请选择一个轮播图',
            'showprice.require' => '展示价格不能为空',
            'showprice.float' => '展示价格只能是数字',
            'postage.float' => '邮费只能是数字',
            'spec_type_id.require' => '商品类型必须',
            'spec_type_id.number' => '商品类型必须是数字',
            'content.require' => '商品详情标题不能为空'];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error($validate->getError());
        }
        //组合轮播图路径
        $param['banner'] = implode('|', $param['banner']);
        //处理富文本
        $content = $param['content'];
        $param['content'] = htmlspecialchars($content);
        $id = $param['id'];
        Db::startTrans();
        try {
            $res = Db::name('market')->strict(false)->where('id', $id)->update($param);
            if (false === $res) {
                exception('基本商品表数据处理错误');
            }
            //处理规格 先删除所有 在新增
            Db::name('market_spec')->where('goods_id', $id)->delete();
            //处理商品规格
            $marketSpecData = [];
            foreach ($param['spec_price'] as $key => $value) {
                $marketSpecData[] = [
                    'goods_id' => $id,
                    'spec_str' => $key,
                    'stock' => $param['spec_stock'][$key],
                    'price' => $value,
                    'image' => $param['image'][$key],
                    'time' => time()
                ];
            }
            if (!empty($marketSpecData)) {
                $result = Db::name('market_spec')->insertAll($marketSpecData);
                if (!$result) {
                    exception("规格添加错误");
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('修改失败' . $e->getMessage());
        }
        $this->success('修改成功', url('index'));
    }

    /*放入回收站*/
    public function delete()
    {
        $id = input('id', 0);
        if ($id == 0) {
            $this->error('参数错误');
        }
        //放入回收站 并且更改下架
        if (db('market')->where('id', $id)->update(['is_del' => '1', 'status' => 0])) {
            $this->success('放入回收站成功');
        } else {
            $this->error('删除失败');
        }
    }

    /*恢复商品*/
    public function isback()
    {
        $id = input('id', 0);
        if ($id == 0) {
            $this->error('参数错误');
        }
        //恢复商品 并且更改上架
        if (db('market')->where('id', $id)->update(['is_del' => '0', 'status' => 1])) {
            $this->success('操作成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 查看回收站
     */
    public function back()
    {
        $param = input();
        $map = [];
        $map[] = ['is_del', '=', '1'];

        //分类
        if (isset($param['cid']) && !empty($param['cid'])) {
            $cid = $param['cid'];
            //如果cid的pid为0 则查询所有子分类id集合
            $cateData = db('marketcate')->find($cid);
            if ($cateData['parent_id'] == 0) {
                $cidCollets = db('marketcate')->where('parent_id', $cid)->select()->toArray();
                $cidColletArr = [];
                foreach ($cidCollets as $cidCollet) {
                    array_push($cidColletArr, $cidCollet['id']);
                }
                $cidColletstr = implode(',', $cidColletArr);
            } else {
                $cidColletstr = $cid;
            }
            $map[] = ['cid', 'in', $cidColletstr];
        }

        //关键字
        if (isset($param['keywords'])) {
            $map[] = ['title', 'like', '%' . $param['keywords'] . '%'];
        }

        $datas = db('market')
            ->alias('m')
            ->field('m.*,c.name cname')
            ->leftJoin('jzb_marketcate c', 'm.cid= c.id')
            ->where($map)
            ->order('id desc')
            ->paginate(10);

        //显示分类
        $tree = new Tree();
        $parentId = $this->request->param("cid", 0, 'intval');
        $result = db('marketcate')->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);
        $this->assign(compact('datas'));
        return $this->fetch();
    }

    /**
     * 永久删除商品
     */
    public function isDelete()
    {
        $id = input('id', 0);
        if ($id == 0) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            //删除该商品
            Db::name('market')->where('id', $id)->delete();
            //同时删除规格表
            Db::name('market_spec')->where('goods_id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('修改失败' . $e->getMessage());
        }
        $this->success('删除成功');
    }

    /**
     * 车品超市取消订单原因编辑
     */
    public function marketSet()
    {
        if (isPost()) {
            $param = input();
            //取消订单原因
            $cancelreasonArr = explode('+', $param['cancelreason']);
            //退款原因
            $backreasonArr = explode('+', $param['backreason']);
            //车品超市客服电话
            $marketkefuArr = explode('+', $param['marketkefu']);
            //插入数据
            $result1 = cmf_set_option('cancelreason', $cancelreasonArr, true);
            $result2 = cmf_set_option('backreason', $backreasonArr, true);
            $result3 = cmf_set_option('marketkefu', $marketkefuArr, true);
            if ($result1 && $result2 && $result3) {
                $this->success('设置成功');
            } else {
                $this->error('设置失败');
            }
        }
        //取消订单原因
        if (!empty($cancelreason = cmf_get_option('cancelreason'))) {
            $cancelreason = implode('+', $cancelreason);
        }
        //退款原因
        if (!empty($backreason = cmf_get_option('backreason'))) {
            $backreason = implode('+', $backreason);
        }
        //车品超市客服电话
        if (!empty($marketkefu = cmf_get_option('marketkefu'))) {
            $marketkefu = implode('+', $marketkefu);
        }
        return view('', compact('cancelreason', 'backreason', 'marketkefu'));
    }

    /*排序*/
    public function goodsorder()
    {
        $param = input('list_orders', '');
        if (!is_array($param) || empty($param)) {
            $this->error('传入类型错误');
        }
        foreach ($param as $key => $vo) {
            $data['list_orders'] = $vo;
            Db::name('market')->where('id', $key)->update($data);
        }
        $this->success("排序更新成功！");
    }
}
